﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;

using Utils;

namespace System.ComponentModel.DataAnnotations
{
    [AttributeUsage(AttributeTargets.Property, Inherited = true)]
    public class RequiredAnyAttribute : ValidationAttribute
    {

        public override bool RequiresValidationContext => true;

        public override string FormatErrorMessage(string name)
        {
            if (string.IsNullOrEmpty(ErrorMessage))
                return $"{name}不能为空";
            return ErrorMessage;
        }
        public override bool IsValid(object value)
        {
            return base.IsValid(value);
        }
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value == null)
            {
                return new ValidationResult(null);
            }

            if (value is string str)
            {
                if (string.IsNullOrWhiteSpace(str))
                {
                    return new ValidationResult(null);
                }
            }
            if (value is ICollection arr)
            {
                if (arr.Count == 0)
                {
                    return new ValidationResult(null);
                }
            }
            var type = value.GetType();
            if (type.IsValueType && type is IComparable comparable)
            {
                if (comparable.CompareTo(Activator.CreateInstance(type)) != 0)
                {
                    return new ValidationResult(null);
                }
            }
            return ValidationResult.Success;
        }
    }

}
